﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Citi.Import.Util;
using Citi.ResourceConsolidation.Domain.Utils;

namespace Citi.ResourceConsolidation.Domain
{
    public partial class JobFunction
    {
        private const string JobFunctionColumn = "Job Function";

        public static readonly List<Definition<JobFunction>> Definitions = new List<Definition<JobFunction>>
            {
                new Definition<JobFunction> { ModelProperty = x => x.Description, MaxLength = 300, Required = true, ColumnName = JobFunctionColumn, CustomConversionMethod = ValidateDescription},
            };

        private static object ValidateDescription(ref JobFunction model, string value, List<string> fields, ref string error, List<string> headers = null)
        {
            if (string.IsNullOrEmpty(value))
            {
                error = string.Format("The field {0} can not be null", JobFunctionColumn);
                return Conversion.Validation.Failed;
            }

            var domain = CacheFacade.Get(new JobFunction().SelectAll<JobFunction>).FirstOrDefault(x => x.Description == value);

            if (domain != null)
            {
                model = domain;
                return Conversion.Validation.Validated;
            }

            return value;
        }

        public static void Save(List<JobFunction> functions)
        {
            functions = functions.Distinct(new JobFunctionComparer()).Where(x => x != null && x.Id == 0).ToList();

            if (!functions.Any()) return;
            functions.First().Save(functions, 100);

            CacheFacade.Clear(typeof(JobFunction));
            Context.ClearContext();
        }
    }

    public class JobFunctionComparer : IEqualityComparer<JobFunction>
    {
        public bool Equals(JobFunction x, JobFunction y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
                return false;

            return x.Description == y.Description && x.Id == y.Id;
        }

        public int GetHashCode(JobFunction item)
        {
            if (ReferenceEquals(item, null)) return 0;

            int hashDescription = item.Description == null ? 0 : item.Description.GetHashCode();
            int hashId = item.Description == null ? 0 : item.Id.GetHashCode();

            return hashDescription ^ hashId;
        }
    }
}
